package com.hbnu.exercise.mysql;

import java.sql.*;

public class DatabaseDemo01
{
    public static void main(String[] args)
    {
        Statement statement = null;
        Connection connection = null;
        try
        {
            // 1.注册驱动
            // DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 2.获取数据库连接
            String url = "jdbc:mysql://localhost:3306/class2210?serverTimezone=GMT&useSSL=false&characterEncoding=utf-8";
            String user = "root";
            String password = "123456";
            connection = DriverManager.getConnection(url, user, password);
            System.out.println(connection);

            // 3.获取数据库操作对象
            statement = connection.createStatement();

            // 4.执行sql
            String sql = "INSERT INTO tb_user(username, password, address, salary) VALUES('李四', '123456', '湖北恩施', 6000.00)";
            // String sql = "UPDATE tb_user SET salary = 8888.0 WHERE id = 1";

            int row = statement.executeUpdate(sql);
            System.out.println(row);

            // 5.处理查询结果集


        } catch (SQLException | ClassNotFoundException e)
        {
            throw new RuntimeException(e);
        } finally
        {
            // 6.关闭数据库资源
            // 资源在关闭时，要从小到大一个一个的关，不要同时关

            try
            {
                if (statement != null)
                    statement.close();
            } catch (SQLException e)
            {
                e.printStackTrace();
            }

            try
            {
                if (connection != null)
                    connection.close();
            } catch (SQLException e)
            {
                e.printStackTrace();
            }
        }
    }
}
